package com.tianci.appstore.controller;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.app.framework.app.LiteAppApplication.ContentAppChangedReceiver.ContentAppChangedReceiverListener;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.PackageReceiver.InstallUninstallInterface;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreBean;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreBeanList;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.tianci.appstore.R;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.ui.data.SkyAppDetailData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListStatusData;
import com.tianci.appstore.ui.search.SearchDataListener;
import com.tianci.appstore.ui.widget.TipToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AppStoreSearchController extends AppStoreBaseController implements InstallUninstallInterface, ContentAppChangedReceiverListener {

    private static AppStoreSearchController instance = null;
    private static Context subContext = null;
    private static final int MAPCOUNT = 20;
    private Map<String, List<SkyListAppData>> searchMap = new HashMap<String, List<SkyListAppData>>();
    private Map<String, Integer> searchCountMap = new HashMap<String, Integer>();
    private List<String> keyList = new ArrayList<String>();
    private List<SkyListAppData> hotSearchList = new ArrayList<SkyListAppData>();
    private SearchDataListener mListener = null;

    public static AppStoreSearchController getAppStoreSearchController() {
        if (null == instance) {
            instance = new AppStoreSearchController(mContext);
        }
        return instance;
    }

    public AppStoreSearchController(Context c) {
        subContext = c;
    }

    public void init() {
        CoocaaApplication.addPackageListener(this);
        LiteAppApplication
                .addContentAppChangedReceiverListener(this);
    }

    public void setSearchDataListener(SearchDataListener listener) {
        mListener = listener;
    }

    public void putMap(String key, List<SkyListAppData> list, int count) {
        if (searchMap == null) {
            return;
        }
        if (searchMap.containsKey(key) && searchCountMap.containsKey(key)) {
            searchMap.remove(key);
            searchMap.put(key, list);
            searchCountMap.remove(key);
            searchCountMap.put(key, count);
            return;
        }
        if (searchMap.size() < MAPCOUNT) {
            keyList.add(key);
            searchMap.put(key, list);
            searchCountMap.put(key, count);
        } else {
            searchMap.remove(keyList.get(0));
            keyList.remove(0);
            searchMap.put(key, list);
            keyList.add(key);
            searchCountMap.put(key, count);
        }
    }

    // 这个方法暂时应该不用
    public void getSearchList(final String key, final int max) {
        if (searchMap != null && searchMap.containsKey(key)) {
            List<SkyListAppData> list = searchMap.get(key);
            // mListener.onAppPageLoaded(); //回调接口
            return;
        }
        new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    Map<String, Object> searchMap = CoocaaApplication.getCoocaaWebService().getAppStoreService().searchApp(key, max);
                    int count = (Integer) searchMap.get("count");
                    List<AppStoreBean> searchList = (List<AppStoreBean>) searchMap.get("list");

                    if (null == searchList || searchList.size() == 0) {
                        return;
                    }

                    List<SkyListAppData> appList = new ArrayList<SkyListAppData>();
                    for (int i = 0; i < searchList.size(); i++) {
                        AppStoreBean bean = searchList.get(i);
                        SkyListStatusData data = new SkyListStatusData(ListType.CGY_APP_LIST);
                        data.setId(bean.id);
                        data.setIconUrl(bean.lmg);
                        data.setPkgName(bean.packagename);
                        data.setShowInfo(getString(R.string.downloaded_count)
                                + String.valueOf(bean.downloads));
                        data.setTitle(bean.name);
                        // AppStatus status = AppStatus.NOT_DOWNLOADED;
                        // try {
                        // status = AppDataProvider.getInstance().getAppStatus(
                        // bean.id, bean.packagename, bean.version);
                        // } catch (RemoteException e) {
                        // // TODO Auto-generated catch block
                        // e.printStackTrace();
                        // }
                        // LogUtils.d("li",
                        // "MSG_GETAPPLIST---" + bean.name + " "
                        // + status.toString());
                        // data.setStatus(status);
                        appList.add(data);
                    }
                    LogUtils.d("lqw", "getSearchList--11-" + appList.size());
                    putMap(key, appList, count);
                    // mListener.onAppPageLoaded(CategoryTypeId, pageindex, appList);
                } catch (AppStoreException e) {
                    // TODO Auto-generated catch block
                    LogAPIForAppStore.reportInterfaceError("根据key搜索应用", Android.throwable2String(e));
                    e.printStackTrace();
                }
            }

        }.start();

    }

    public void getSearchList(final String key, final int pageIndex, final int pageCount, final boolean isGame) {
        if (searchMap != null && searchCountMap != null && searchMap.containsKey(key)
                && searchCountMap.containsKey(key) && pageIndex == 1) {
            List<SkyListAppData> list = searchMap.get(key);
            int count = searchCountMap.get(key);
            mListener.onAppPageLoaded(key, pageIndex, count, list);
//            for(SkyListAppData data:list)
//            {
//                SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
//                status = AppDataProvider.getInstance().isAppInstalled(data.getPkgName());
//                refreshStatus(data.getPkgName(),status);
//            }
            return;
        }
        new Thread() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    // killTimer(TimerType.APP_SEARCH);
                    // startTimer(TimerType.APP_SEARCH, mSearchHandler, key);
                    int count = 0;
                    List<AppStoreBean> searchList = null;
                    if (isGame) {
                        AppStoreBeanList list = CoocaaApplication.getCoocaaWebService().getAppStoreService().searchGames(key, pageIndex, pageCount);
                        if (list != null) {
                            count = Integer.valueOf(list.count);
                            searchList = list.data;
                        }
                    } else {
                        Map<String, Object> searchMap = CoocaaApplication.getCoocaaWebService().getAppStoreService().searchApp(key, pageIndex,
                                pageCount);
                        count = (Integer) searchMap.get("count");
                        searchList = (List<AppStoreBean>) searchMap.get("list");
                    }
                    if (null == searchList || searchList.size() == 0) {
                        mListener.onAppPageLoaded(key, pageIndex, 0, null);
                        return;
                    }
                    List<SkyListAppData> appList = new ArrayList<SkyListAppData>();
                    for (int i = 0; i < searchList.size(); i++) {
                        AppStoreBean bean = searchList.get(i);
                        SkyListStatusData data = new SkyListStatusData(ListType.CGY_APP_LIST);
                        data.setId(bean.id);
                        data.setIconUrl(bean.lmg);
                        data.setPkgName(bean.packagename);
                        data.setShowInfo(getString(R.string.downloaded_count)
                                + String.valueOf(bean.downloads));
                        data.setTitle(bean.name);
                        data.setGame(isGame);
                        SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
                        status = AppDataProvider.getInstance().isAppInstalled(bean.packagename);
                        data.setStatus(status);
                        appList.add(data);
                    }

                    LogUtils.d("lqw", "getSearchList--22-" + appList.size());
                    if (pageIndex == 1) {
                        putMap(key, appList, count);
                    }
                    mListener.onAppPageLoaded(key, pageIndex, count, appList);
                } catch (AppStoreException e) {
                    // TODO Auto-generated catch block
                    LogAPIForAppStore.reportInterfaceError("根据key搜索游戏或者应用", Android.throwable2String(e));
                    LogUtils.d("lqw", "AppStoreException:" + e);
                    if (isGame) {
                        LogAPIForAppStore.reportInterfaceError("根据拼音查询游戏", Android.throwable2String(e));
                    }
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            mListener.onAppPageLoaded(key, pageIndex, 0, null);
                            TipToast.getInstance(mContext).showTipToast("获取后台数据超时！");
                        }
                    });
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void getSearchRanking(final boolean isGame) {
        if (hotSearchList != null && hotSearchList.size() > 0) {
            mListener.onHotAppLoaded(hotSearchList);
//            for(SkyListAppData data:hotSearchList)
//            {
//                SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
//                status = AppDataProvider.getInstance().isAppInstalled(data.getPkgName());
//                refreshStatus(data.getPkgName(),status);
//            }
            return;
        }
        new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    // killTimer(TimerType.APP_SEARCH);
                    // startTimer(TimerType.APP_SEARCH, mSearchHandler, "");
                    List<AppStoreBean> searchList = null;
                    if (isGame) {
                        AppStoreBeanList list = CoocaaApplication.getCoocaaWebService().getAppStoreService().getPopularOnSearch();
                        if (list != null) {
                            searchList = list.data;
                        }
                    } else {
                        searchList = CoocaaApplication.getCoocaaWebService().getAppStoreService().getSearchRanking();
                    }
                    // killTimer(TimerType.APP_SEARCH);
                    if (null == searchList || searchList.size() == 0) {
                        mListener.onHotAppLoaded(null);
                        return;
                    }

                    List<SkyListAppData> appList = new ArrayList<SkyListAppData>();
                    for (int i = 0; i < searchList.size(); i++) {
                        AppStoreBean bean = searchList.get(i);
                        SkyListStatusData data = new SkyListStatusData(ListType.CGY_APP_LIST);
                        data.setId(bean.id);
                        data.setIconUrl(bean.lmg);
                        data.setPkgName(bean.packagename);
                        data.setShowInfo(getString(R.string.downloaded_count)
                                + String.valueOf(bean.downloads));
                        data.setTitle(bean.name);
                        data.setGame(isGame);
                        SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
                        status = AppDataProvider.getInstance().isAppInstalled(bean.packagename);
                        data.setStatus(status);
                        appList.add(data);
                    }
                    LogUtils.d("lqw", "getSearchList--22-" + appList.size());
                    hotSearchList.clear();
                    hotSearchList.addAll(appList);
                    mListener.onHotAppLoaded(appList);
                } catch (AppStoreException e) {
                    // TODO Auto-generated catch block
                    LogAPIForAppStore.reportInterfaceError("获取热门搜索游戏获取应用", Android.throwable2String(e));
                    LogUtils.d("lqw", "AppStoreException:" + e);
                    if (isGame) {
                        LogAPIForAppStore.reportInterfaceError("搜索页热门游戏", Android.throwable2String(e));
                    }
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            mListener.onHotAppLoaded(null);
                            TipToast.getInstance(mContext).showTipToast("获取后台数据超时！");
                        }
                    });
                    e.printStackTrace();
                }
            }

        }.start();
    }

    public Handler mSearchHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            String key = (String) msg.obj;
            LogUtils.d("lqw", "get app detail outtime " + key);
            if (key.equals("")) {
                mListener.onHotAppLoaded(null);
            } else {
                mListener.onAppPageLoaded(key, 0, 0, null);
            }
            TipToast.getInstance(mContext).showTipToast("获取后台数据有点慢！");
        }

    };

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        CoocaaApplication.removePackageListener(this);
        LiteAppApplication.removeContentAppChangedReceiverListener(this);
        mListener = new SearchDataListener() {
            @Override
            public void onAppPageLoaded(String key, int pageIndex, int count, List<SkyListAppData> appList) {

            }

            @Override
            public void onHotAppLoaded(List<SkyListAppData> appList) {

            }

            @Override
            public void onRefreshAppStatus(String pkg, SkyAppDetailData.AppStatus status) {

            }
        };
    }

    private void refreshStatus(String pkg, SkyAppDetailData.AppStatus status) {
        if (mListener != null)
            mListener.onRefreshAppStatus(pkg, status);   //更新的回调
    }

    @Override
    public void installEvent(Intent i) {
        LogUtils.d("intent", "installEvent--pkg:" + i.getData().getSchemeSpecificPart());
        String pkg = i.getData().getSchemeSpecificPart();
        refreshStatus(pkg, SkyAppDetailData.AppStatus.INSTALLED);
    }

    @Override
    public void uninstallEvent(Intent i) {
        LogUtils.d("intent", "installEvent--pkg:" + i.getData().getSchemeSpecificPart());
        String pkg = i.getData().getSchemeSpecificPart();
        refreshStatus(pkg, SkyAppDetailData.AppStatus.NOT_DOWNLOADED);
    }

    @Override
    public void onAction(Intent i) {
        String[] pkgArray = null;
        if (i != null)
            pkgArray = i.getStringArrayExtra("extra");
        if (pkgArray != null && pkgArray.length > 0) {
            LogUtils.d("test", "onAction list pkg:" + pkgArray.length);
            for (String pkg : pkgArray) {
                if (pkg != null && !pkg.equals("")) {
                    SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
                    status = AppDataProvider.getInstance().isAppInstalled(pkg);
                    refreshStatus(pkg, status);
                }
            }
        }
    }
}
